<!--
	作者：2575202388@qq.com
	时间：2018-10-14
	描述：前端分页组件
-->
<template>
	<Page @on-change="Change" @on-page-size-change="changesize" :current="current" :total="total" :show-elevator="showelevator" :page-size="pagesize" :show-sizer="showsizer" :placement="placement" :transfer="transfer" :page-size-opts="pagesizeopts">

	</Page>
</template>

<script>
	export default {
		name: "Webpage",
		props: {
			serverUrl: {
				type: String,
				default: ""
			},
			paramiters: {
				type: Object,
				default: function() {
					return {};
				}
			},
			datas: {
				type: Array,
				default: function() {
					return [];
				}
			},
			type: {
				type: String,
				default: function() {
					return "post";
				}
			},
			renderBefor: {
				type: Function,
				default: function() {
					return null;
				}
			}
		},
		data() {
			return {
				current: 1,
				total: 0,
				pagesizeopts: [5, 10, 20, 50, 100],
				size: "default",
				showelevator: true,
				showsizer: true,
				placement: "top",
				transfer: true,
				pagesize: 10,
				_datas: []
			}
		},
		methods: {
			Change(currentPage) {
				this.current = currentPage;
				this.changedata();
			},
			changesize(pagesize) {
				this.pagesize = pagesize;
				this.changedata();
			},
			changedata() {
				this.$emit("loading", true);
				var _datas = [];
				var startindex = (this.current - 1) * this.pagesize;
				var endindex = this.current * this.pagesize;
				endindex = endindex > this._datas.length ? this._datas.length : endindex;
				for(let index = startindex; index < endindex; index++) {
					let target = this._datas[index];
					if(target) {
						_datas.push(target);
					}
				}
				this.$emit('pagechange', _datas);
				this.$emit("loading", false);
			},
			getdatas() {
				this.$emit("loading", true);
				this.gethttp().then(result => {
						this.initdatas(result.data);
					})
					.catch(() => {
						this.$emit("loading", false);
					})
			},
			initdatas(data) {
				this._datas = this.renderBefor(data);
				if(!this._datas) {
					this._datas = data;
				}
				this.total = this._datas.length;
				this.changedata();
			},
			gethttp() {
				if(this.type == "post") {
					return this.$http.post(this.serverUrl, this.paramiters);
				} else if(this.type == "get") {
					return this.$http.get(this.serverUrl);
				}
			}
		},
		watch: {
			serverUrl: {
				handler: function() {
					this.getdatas();
				},
				deep: true
			},
			paramiters: {
				handler: function() {
					this.getdatas();
				},
				deep: true
			},
			datas: {
				handler: function(newdatas) {
					this._datas = newdatas;
				},
				deep: true
			}
		},
		mounted() {
			this.initdatas([...this.datas]);
		}
	}
</script>

<style>

</style>